package ai.leinao.notify.dingtalk;

import ai.leinao.notify.core.template.Template;
import ai.leinao.notify.core.template.TemplateProperties;
import ai.leinao.notify.core.template.VariableDefinition;
import ai.leinao.notify.dingtalk.domain.DingTalkRobotMarkDown;
import ai.leinao.notify.dingtalk.domain.DingTalkRobotText;
import ai.leinao.notify.dingtalk.enums.DingTalkMessageType;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONObject;
import lombok.Getter;
import lombok.Setter;

import java.util.HashMap;
import java.util.Map;

/**
 * 钉钉机器人模板
 *
 * @author zhong.wang
 * @date 2025/7/11
 */
@Getter
@Setter
public class DingTalkRobotTemplate implements Template {
    /**
     * 模板ID
     */
    private String templateId;

    /**
     * 消息类型
     */
    private DingTalkMessageType messageType;

    /**
     * 消息内容
     */
    private DingTalkRobotText text;

    /**
     * markdown消息内容
     */
    private DingTalkRobotMarkDown markdown;

    /**
     * 变量池
     */
    private Map<String, VariableDefinition> variables;

    /**
     * 获取模板ID
     *
     * @return
     */
    @Override
    public String getTemplateId() {
        return templateId;
    }


    /**
     * 创建模板
     * @param properties
     * @return
     */
    public DingTalkRobotTemplate of(TemplateProperties properties) {
        if(CollUtil.isEmpty(variables)){
            variables = new HashMap<>();
        }
        String messageType = properties.getTemplate().get("messageType").toString();
        this.messageType = DingTalkMessageType.getDingTalkMessageType(messageType);
        if(messageType.equals(DingTalkMessageType.TEXT.getType())){
            this.text = new DingTalkRobotText(properties.getTemplate().get("text").toString());
        }else{
            this.markdown = new DingTalkRobotMarkDown(properties.getTemplate().get("title").toString(), properties.getTemplate().get("text").toString());
        }
        this.templateId = properties.getId();
        //动态配置的变量
        if (null != properties.getVariableDefinitions()) {
            for (VariableDefinition embeddedVariable : properties.getVariableDefinitions()) {
                this.variables.put(embeddedVariable.getId(), embeddedVariable);
            }
        }
        return this;
    }

   public JSONObject toJson(Map<String, Object> context) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("msgtype", messageType.getType());
        if (messageType == DingTalkMessageType.TEXT) {
            jsonObject.put("text", text.render(context).toJson());
        } else if (messageType == DingTalkMessageType.MARKDOWN) {
            jsonObject.put("markdown", markdown.render(context).toJson());
        }
        return jsonObject;
    }
}
